import time
import datetime
import threading

class Queue(object):

    def __init__(self, error_email=None,
                 error_email_from='robot@localhost',
                 smtp_server='localhost'):
        self.error_email = error_email
        self.error_email_from = error_email_from
        self.smtp_server = smtp_server
        self._queue = []
        self._activate_event = threading.Event()

    def add_task(self, task):
        task.start_on_queue(self)
        
    def schedule(self, task, time):
        self._queue.append((time, task))
        self._queue.sort()
        self._activate_event.set()

    def run(self):
        while 1:
            timeout = self.run_one_queue()
            self._activate_event.wait(timeout)

    def run_one_queue(self):
        if not self._queue:
            # @@: timeout or something?
            self._activate_event.wait()
            assert self._queue
            return 0
        
        next_time = self._queue[0][0]
        now = datetime.datetime.now()
        if now > next_time:
            # happening right now!
            self.run_next_task()
            return 0

        return (next_time - now).seconds

    def run_next_task(self):
        next_time, next_task = self._queue.pop(0)
        next_task.execute(self)

        
